import express from 'express';
import cors from 'cors';
import fs from 'fs';
import path from 'path';

// Load env from victory.env if present
const victoryEnvPath = path.resolve(process.cwd(), 'victory.env');
if (fs.existsSync(victoryEnvPath)) {
  const content = fs.readFileSync(victoryEnvPath, 'utf-8');
  for (const line of content.split(/\r?\n/)) {
    const m = line.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
    if (m) {
      const key = m[1];
      const val = m[2];
      if (!(key in process.env)) {
        process.env[key] = val;
      }
    }
  }
}

const app = express();
app.use(cors());
app.use(express.json({ limit: '1mb' }));

const PORT = Number(process.env.PORT || 8787);
const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY || '';
const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/chat/completions';
const DEFAULT_MODEL = process.env.DEEPSEEK_MODEL || 'deepseek-chat';

// 豆包API配置
const DOUBAO_API_KEY = process.env.DOUBAO_API_KEY || '2f47aacd-c91a-4b3e-816e-7b766bc574b2';
const DOUBAO_API_URL = 'https://ark.cn-beijing.volces.com/api/v3/chat/completions';
const DOUBAO_MODEL = process.env.DOUBAO_MODEL || 'doubao-1-5-thinking-pro-250415';

if (!DEEPSEEK_API_KEY) {
  console.warn('[warn] DEEPSEEK_API_KEY is not set. Set it in victory.env or environment.');
}
if (!DOUBAO_API_KEY) {
  console.warn('[warn] DOUBAO_API_KEY is not set. Set it in victory.env or environment.');
}

app.post('/api/chat', async (req, res) => {
  try {
    const { messages, model } = req.body || {};
    if (!Array.isArray(messages) || messages.length === 0) {
      return res.status(400).json({ error: 'messages is required' });
    }
    if (!DEEPSEEK_API_KEY) {
      return res.status(500).json({ error: 'Server missing DEEPSEEK_API_KEY' });
    }

    const response = await fetch(DEEPSEEK_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`
      },
      body: JSON.stringify({
        model: model || DEFAULT_MODEL,
        messages,
        temperature: 0.7,
        stream: false
      })
    });

    if (!response.ok) {
      const text = await response.text();
      console.error('[deepseek] error', response.status, text);
      return res.status(response.status).json({ error: 'Upstream error', detail: text });
    }

    const data = await response.json();
    const reply = data?.choices?.[0]?.message?.content ?? '';
    return res.json({ reply, raw: data });
  } catch (err: any) {
    console.error('[deepseek] unexpected', err);
    return res.status(500).json({ error: 'Unexpected server error', detail: err?.message || String(err) });
  }
});

// Simple GET to verify server is ours
app.get('/api/chat', (_req, res) => {
  res.status(405).send('Use POST /api/chat');
});

app.get('/api/health', (_req, res) => {
  res.json({ ok: true });
});

// 豆包API端点
app.post('/api/chat/doubao', async (req, res) => {
  try {
    const { messages, model } = req.body || {};
    if (!Array.isArray(messages) || messages.length === 0) {
      return res.status(400).json({ error: 'messages is required' });
    }
    if (!DOUBAO_API_KEY) {
      return res.status(500).json({ error: 'Server missing DOUBAO_API_KEY' });
    }

    const response = await fetch(DOUBAO_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${DOUBAO_API_KEY}`
      },
      body: JSON.stringify({
        model: model || DOUBAO_MODEL,
        messages,
        temperature: 0.7,
        stream: false
      })
    });

    if (!response.ok) {
      const text = await response.text();
      console.error('[doubao] error', response.status, text);
      return res.status(response.status).json({ error: 'Upstream error', detail: text });
    }

    const data = await response.json();
    const reply = data?.choices?.[0]?.message?.content ?? '';
    return res.json({ reply, raw: data });
  } catch (err: any) {
    console.error('[doubao] unexpected', err);
    return res.status(500).json({ error: 'Unexpected server error', detail: err?.message || String(err) });
  }
});

app.get('/api/chat/doubao', (_req, res) => {
  res.status(405).send('Use POST /api/chat/doubao');
});

app.get('/api/debug', async (_req, res) => {
  try {
    if (!DEEPSEEK_API_KEY) {
      return res.status(500).json({ ok: false, error: 'Missing DEEPSEEK_API_KEY' });
    }
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), 20000);
    const resp = await fetch(DEEPSEEK_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`
      },
      body: JSON.stringify({
        model: DEFAULT_MODEL,
        messages: [
          { role: 'system', content: '你是一个简洁助手。' },
          { role: 'user', content: '用一句话回复：测试是否可用。' }
        ],
        temperature: 0.2,
        stream: false
      }),
      signal: controller.signal
    });
    clearTimeout(timer);
    const text = await resp.text();
    if (!resp.ok) {
      console.error('[debug] upstream failed', resp.status, text);
      return res.status(resp.status).json({ ok: false, status: resp.status, body: text });
    }
    let data: any;
    try { data = JSON.parse(text); } catch { data = { raw: text }; }
    const reply = data?.choices?.[0]?.message?.content ?? '';
    return res.json({ ok: true, reply, model: DEFAULT_MODEL });
  } catch (e: any) {
    console.error('[debug] exception', e);
    return res.status(500).json({ ok: false, error: e?.message || String(e) });
  }
});

// 豆包API调试端点
app.get('/api/debug/doubao', async (_req, res) => {
  try {
    if (!DOUBAO_API_KEY) {
      return res.status(500).json({ ok: false, error: 'Missing DOUBAO_API_KEY' });
    }
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), 20000);
    const resp = await fetch(DOUBAO_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${DOUBAO_API_KEY}`
      },
      body: JSON.stringify({
        model: DOUBAO_MODEL,
        messages: [
          { role: 'system', content: '你是人工智能助手.' },
          { role: 'user', content: '你好' }
        ],
        temperature: 0.7,
        stream: false
      }),
      signal: controller.signal
    });
    clearTimeout(timer);
    const text = await resp.text();
    if (!resp.ok) {
      console.error('[debug doubao] upstream failed', resp.status, text);
      return res.status(resp.status).json({ ok: false, status: resp.status, body: text });
    }
    let data: any;
    try { data = JSON.parse(text); } catch { data = { raw: text }; }
    const reply = data?.choices?.[0]?.message?.content ?? '';
    return res.json({ ok: true, reply, model: DOUBAO_MODEL });
  } catch (e: any) {
    console.error('[debug doubao] exception', e);
    return res.status(500).json({ ok: false, error: e?.message || String(e) });
  }
});

app.listen(PORT, () => {
  console.log(`[server] API proxy running on http://localhost:${PORT}`);
  console.log(`[server] DeepSeek API: POST /api/chat`);
  console.log(`[server] Doubao API: POST /api/chat/doubao`);
});


